package com.ruoyi.web.controller.app;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.model.LoginAppUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.file.utils.MinioTool;
import com.ruoyi.framework.web.service.AppTokenService;
import com.ruoyi.system.service.IAppUserService;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import static com.ruoyi.common.constant.Constants.APP_API_PREFIX;

@Api("APP用户登录管理")
@RestController
@RequestMapping(APP_API_PREFIX + "/user")
public class AppUserController extends BaseController {
    @Resource
    private MinioTool minioTool;
    @Resource
    private IAppUserService appUserService;
    @Resource
    private AppTokenService appTokenService;

    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile() {
        LoginAppUser loginAppUser = SecurityUtils.getLoginAppUser();
        AppUser user = loginAppUser.getAppUser();
        return AjaxResult.success(user);
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarFile") MultipartFile avatarFile) throws Exception {
        if (!avatarFile.isEmpty()) {
            LoginAppUser loginAppUser = getLoginAppUser();
            String url = minioTool.uploadMinio(avatarFile);

//            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            if (appUserService.updateAppUserAvatar(loginAppUser.getUsername(), url)) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", url);
                // 更新缓存用户头像
                loginAppUser.getAppUser().setAvatar(url);
                appTokenService.setLoginAppUser(loginAppUser);
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }
}
